﻿Imports System
Imports System.IO
Imports maxFAH.clsHWInfo
Imports System.Xml
Public Class frmHWINFO
    Public Event SetupDone()
    Private WithEvents fEULA As New frmEULA
    Private WithEvents Message As frmMessage
    'Checks if the function exists on this OS, then calls it.
    Private _noupdate As Boolean = False
    Private Sub frmHWINFO_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Visible = False
            fEULA.Show()
            While fEULA.Visible
                Application.DoEvents()
            End While
            If Not bEULA Then End
            If Not Cfg.CfgManager.SetupManager.LoadWebXML(Xlocation) Then
                MsgBox("Could not connect to web based setup information, application forced to exit.")
                Application.Exit()
            End If
            hwInfo.doWMI()
            With hwInfo
                lblWindowsVersion.Text = hwInfo.OsName
                _noupdate = True
                If (.TotalCores >= 2 And Not .HasHT) Or (.TotalCores >= 4) Then
                    'Remove comment note's and reenable combobox for multi smp install
                    'cmbSmpCores.Enabled = True
                    'cmbSmpCores.Text = .SmpC
                    txtAcPass.Enabled = True
                    rbSMP.Checked = True
                    pnClientType.Enabled = True
                    If .IsX64 Then
                        chk64.Checked = True
                        rbDeino.Enabled = False
                        rbMPICH.Checked = True
                    Else
                        chk64.Checked = False
                        rbDeino.Enabled = True
                        rbDeino.Checked = True
                        rbMPICH.Enabled = True
                    End If
                Else
                    rbUni.Checked = True
                    pnClientType.Enabled = False
                    rbMPICH.Checked = False
                    rbDeino.Checked = False
                    cmbSmpCores.Enabled = False
                    txtAcPass.Enabled = False
                    chk64.Checked = .IsX64
                    rbDeino.Enabled = False
                    rbMPICH.Enabled = False
                    rbDeino.Checked = False
                    rbMPICH.Checked = False
                End If
                _noupdate = False
                chkOsSupported.Checked = .OSSupported
                .FillGpuCMB(cmbGPU)
                .FillCpuCMB(cmbProcessor)
                lblUserName.Text = .CurrentUser
                chkAdmin.Checked = .IsAdmin
                If Not .IsAdmin Or Not .OSSupported Then
                    If Not .IsAdmin Then
                        MsgBox("You need admin rights!", MsgBoxStyle.MsgBoxSetForeground)
                    Else
                        MsgBox("OS not supported!", MsgBoxStyle.MsgBoxSetForeground)
                    End If
                End If
            End With
            If rbDeino.Checked Then
                hwInfo.FillTV(tvClients, eSMPtype.Deino)
            ElseIf rbMPICH.Checked Then
                hwInfo.FillTV(tvClients, eSMPtype.Mpich)
            Else
                hwInfo.FillTV(tvClients)
            End If
            formHWinfo.Text = My.Application.Info.Version.ToString
        Catch ex As Exception
            MsgBox(ex.Message)
            End
        End Try

    End Sub


    Private Sub Message_CancelClicked() Handles Message.CancelClicked

    End Sub

    Private Sub Message_NextClicked() Handles Message.NextClicked
        Message.Visible = False
        Me.Visible = True
    End Sub

    Private Sub cmbProcessor_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbProcessor.SelectedIndexChanged
        Try
            Dim tCpu As InstalledCPU
            tCpu = hwInfo.GetCpu(cmbProcessor.SelectedIndex + 1)
            lblCores.Text = tCpu.NumberOfCores.ToString
            chkHT.Checked = tCpu.HasHT
        Catch ex As Exception

        End Try
    End Sub

    Private Sub cmbGPU_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbGPU.SelectedIndexChanged
        Try
            Dim tGpu As InstalledGPU
            tGpu = hwInfo.GetGpu(cmbGPU.SelectedIndex + 1)
            chkFolds.Checked = tGpu.CanFold

        Catch ex As Exception

        End Try
    End Sub



    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Application.Exit()
    End Sub
    Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As LogonType, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer
    Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal hObject As IntPtr) As Boolean
    Public Enum LogonType As Integer
        LOGON32_LOGON_INTERACTIVE = 2
        LOGON32_LOGON_NETWORK = 3
        LOGON32_LOGON_BATCH = 4
        LOGON32_LOGON_SERVICE = 5
        LOGON32_LOGON_UNLOCK = 7
        LOGON32_LOGON_NETWORK_CLEARTEXT = 8
        LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    Public Function IsNTPasswordValid(ByVal Username As String, ByVal Password As String, Optional ByVal Domain As String = "") As Boolean
        Dim Token As New IntPtr
        LogonUser(Username, Domain, Password, LogonType.LOGON32_LOGON_INTERACTIVE, 0, Token)
        CloseHandle(Token)
        If Token.ToInt32 <> 0 Then Return True
    End Function


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdinstall.Click
        'no clients selected 
        cmdinstall.Enabled = False
        Dim DoInstall As Boolean = False, doSMP As Boolean = False
        For Each cNode As TreeNode In tvClients.Nodes
            If cNode.Checked = True Then
                DoInstall = True
                If cNode.Tag < clsClientConfiguration.clsClientConfigs.eClient.GXN Then
                    doSMP = True
                End If
            End If
        Next

        If doSMP Then
            If txtAcPass.TextLength = 0 Then
                MsgBox("For automated SMP installations, you need to enter the account password. If your admin account does not have a password, setup can also not continue.", MsgBoxStyle.MsgBoxSetForeground)
                cmdinstall.Enabled = True
                Exit Sub
            Else
                'Do account check here
                If Not IsNTPasswordValid(Mid(hwInfo.CurrentUser, hwInfo.CurrentUser.LastIndexOf("\") + 2), txtAcPass.Text) Then
                    MsgBox("The password does not match the current user.", MsgBoxStyle.MsgBoxSetForeground)
                    cmdinstall.Enabled = True
                    txtAcPass.Focus()
                    Exit Sub
                Else
                    hwInfo.AccPassword = txtAcPass.Text
                End If
            End If
        End If

        If Not DoInstall Then
            cmdinstall.Enabled = True
            MsgBox("You need to select which clients to install by checking their corresponding checkboxes", MsgBoxStyle.MsgBoxSetForeground)
            Exit Sub
        End If
        Me.Visible = False
        'get checked nodes
        Cfg.CfgManager.SetupManager.CreateRoot(txtLocation.Text)
        DownloadZIP(txtLocation.Text & "\ICSharpCode.SharpZipLib.dll")
        For Each tnode As TreeNode In tvClients.Nodes
            If tnode.Checked Then
                Cfg.CfgManager.SetupManager.DownloadClient(tnode.Tag)
                Select Case tnode.Tag
                    Case Cfg.CfgManager.SetupManager.eClient.GVA
                        Cfg.CfgManager.SetupManager.AddGpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.eClient.GVN
                        Cfg.CfgManager.SetupManager.AddGpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.eClient.GXA
                        Cfg.CfgManager.SetupManager.AddGpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.eClient.GXN
                        Cfg.CfgManager.SetupManager.AddGpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.eClient.SVD
                        Cfg.CfgManager.SetupManager.AddCpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.eClient.SVM
                        Cfg.CfgManager.SetupManager.AddCpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.eClient.SXD
                        Cfg.CfgManager.SetupManager.AddCpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.eClient.SXM
                        Cfg.CfgManager.SetupManager.AddCpuClient(tnode.Tag)
                    Case Cfg.CfgManager.SetupManager.AddCpuClient(tnode.Tag)
                        Cfg.CfgManager.SetupManager.AddCpuClient(tnode.Tag)
                End Select
            End If
        Next
        'clients installed and configured!
        Cfg.CfgManager.ClearAfterInstall()
        LoadClients()
        Dim frmAF As New frmClientAffinity
        frmAF.StartPosition = FormStartPosition.CenterScreen
        frmAF.Show()
    End Sub
    Public Sub CloseHWinfo()
        Try
            My.Computer.FileSystem.CopyFile(Application.ExecutablePath, mPath & "\maxFAH.exe", True)
            Try
                My.Computer.FileSystem.CopyFile(Application.StartupPath & "\CUDA.NET.DLL", mPath & "\CUDA.NET.DLL", True)
                My.Computer.FileSystem.CopyFile(Application.StartupPath & "\ICSharpCode.SharpZipLib.dll", mPath & "\ICSharpCode.SharpZipLib.dll", True)
                My.Computer.FileSystem.CopyFile(Application.StartupPath & "\Interop.IWshRuntimeLibrary.dll", mPath & "\Interop.IWshRuntimeLibrary.dll", True)
            Catch ex As Exception
                MsgBox("An error occured when copying dll files to install location")
            End Try
            Dim strDesktop As String = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
            Dim strStartMenu As String = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)
            CreateTray(mPath, strDesktop & "\Start maxFAH.lnk", "Start maxFAH")
            CreateTray(mPath, strStartMenu & "\Start maxFAH.lnk", "Start maxFAH")
        Catch ex As Exception
            MsgBox("Could not create shortcuts for some reason!")
            Application.Exit()
        End Try
        MsgBox("Installation done, shortcuts added to desktop and startmenu!")
        Me.Close()
        Application.Exit()
    End Sub
    Private Sub lblUserName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblUserName.Click
        Try
            If lblUserName.Text.Contains("#####") Then
                lblUserName.Text = hwInfo.CurrentUser
            Else
                lblUserName.Text = "#####"
            End If
        Catch ex As Exception

        End Try
    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Private Sub FAQToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FAQToolStripMenuItem.Click
        Dim cinfo As clsClientConfiguration.clsClientConfigs.sSetupManager.sClientInfo = Cfg.CfgManager.SetupManager.ClientInfo(tvClients.SelectedNode().Tag)
        If cinfo.Faq = Nothing Then Exit Sub
        Process.Start(cinfo.Faq)
    End Sub

    Private Sub GuideToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GuideToolStripMenuItem.Click
        Dim cinfo As clsClientConfiguration.clsClientConfigs.sSetupManager.sClientInfo = Cfg.CfgManager.SetupManager.ClientInfo(tvClients.SelectedNode().Tag)
        If cinfo.Faq = Nothing Then Exit Sub
        Process.Start(cinfo.Guide)
    End Sub

    Private Sub frmHWINFO_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        'Remove commenting if needed
        'If txtAcPass.Enabled Then txtAcPass.Focus()
    End Sub

    Private Sub rbMPICH_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbMPICH.CheckedChanged
        If _noupdate Then Exit Sub
        If rbDeino.Checked Then
            hwInfo.FillTV(tvClients, eSMPtype.Deino)
        ElseIf rbMPICH.Checked Then
            hwInfo.FillTV(tvClients, eSMPtype.Mpich)
        Else
            hwInfo.FillTV(tvClients)
        End If
    End Sub

    Private Sub rbDeino_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbDeino.CheckedChanged
        If _noupdate Then Exit Sub
        If rbDeino.Checked Then
            hwInfo.FillTV(tvClients, eSMPtype.Deino)
        ElseIf rbMPICH.Checked Then
            hwInfo.FillTV(tvClients, eSMPtype.Mpich)
        Else
            hwInfo.FillTV(tvClients)
        End If
    End Sub

    Private Sub cmbSmpCores_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbSmpCores.SelectedIndexChanged
        If _noupdate Then Exit Sub
        hwInfo.SmpC = cmbSmpCores.Text
        If rbDeino.Checked Then
            hwInfo.FillTV(tvClients, eSMPtype.Deino)
        ElseIf rbMPICH.Checked Then
            hwInfo.FillTV(tvClients, eSMPtype.Mpich)
        Else
            hwInfo.FillTV(tvClients)
        End If
    End Sub

    Private Sub cmdLocation_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLocation.Click
        Try
            fbDialog.ShowNewFolderButton = True
            If fbDialog.ShowDialog Then
                If fbDialog.SelectedPath <> "" Then
                    txtLocation.Text = fbDialog.SelectedPath
                    txtLocation.TextAlign = HorizontalAlignment.Left
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub txtLocation_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtLocation.KeyPress
        e.Handled = True
    End Sub

    Private Sub txtLocation_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles txtLocation.MouseClick
        Try
            Call cmdLocation_Click(Me, Nothing)
        Catch ex As Exception

        End Try
    End Sub



    Private Sub txtLocation_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtLocation.TextChanged
        Try
            cmdinstall.Enabled = txtLocation.TextLength <> 0
        Catch ex As Exception

        End Try
    End Sub





    Private Sub tvClients_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles tvClients.AfterCheck
        If e.Action = TreeViewAction.Unknown Then Exit Sub
        Dim _En As Boolean = False
        For Each tItem As TreeNode In tvClients.Nodes
            If tItem.Checked And CInt(tItem.Tag) < 5 Then _En = True
        Next
        txtAcPass.Enabled = _En
    End Sub



    Private Sub rbUni_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbUni.CheckedChanged
        Try
            If rbUni.Checked Then
                pnSmpType.Enabled = False
                rbDeino.Checked = False
                rbMPICH.Checked = False
                txtAcPass.Enabled = False
                txtAcPass.Text = ""
                If txtLocation.TextAlign <> HorizontalAlignment.Center Then
                    cmdinstall.Enabled = True
                Else
                    cmdinstall.Enabled = False
                End If
            Else
                pnSmpType.Enabled = True
                pnClientType.Enabled = True
                If hwInfo.IsX64 Then
                    rbMPICH.Checked = True
                Else
                    rbDeino.Checked = True
                End If
                txtAcPass.Enabled = True
                If txtAcPass.TextLength > 0 Then
                    cmdinstall.Enabled = True
                Else
                    cmdinstall.Enabled = False
                    txtAcPass.Focus()
                End If
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub txtAcPass_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAcPass.TextChanged
        If pnSmpType.Enabled And txtLocation.TextAlign <> HorizontalAlignment.Center Then
            cmdinstall.Enabled = True
        Else
            cmdinstall.Enabled = False
        End If
    End Sub
End Class